package cn.satoken.controller;

import cn.dev33.satoken.util.SaResult;
import cn.satoken.entity.CrmFile;
import cn.satoken.service.FileService;
import cn.satoken.service.impl.MinioService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * <h3>saToken</h3>
 * <p></p>
 *
 * @author gdw
 * @since 2025-05-28 15:53:53
 */
@RestController
@RequestMapping("/files/")
@RequiredArgsConstructor
public class FileController {
    private final MinioService minioService;
    private final FileService fileService;
    //上传方法
    @PostMapping("upload")
    public SaResult upload(@RequestParam("file") MultipartFile file) throws Exception {
        return minioService.uploadFile(file);
    }
    //下载方法
    @PostMapping("download")
    public void downloadFile(@RequestBody CrmFile file, HttpServletResponse response) {
        String fileUrl = file.getUrl();
        try (InputStream inputStream = minioService.downloadFile(fileUrl);
             OutputStream out = response.getOutputStream()) {

            // 提取文件名
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            fileName = URLDecoder.decode(fileName, StandardCharsets.UTF_8.name());

            // 设置下载响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" +
                    URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20") + "\"");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);

            // 写入文件内容
            byte[] buffer = new byte[4096];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    //文件类型格式封装
    @PostMapping("delete")
    public SaResult deleteFile(@RequestBody CrmFile crmfile) throws Exception {
        //1.删除minio中的文件数据
        if (crmfile.getUrl()==null||"".equals(crmfile.getUrl())) {
            return SaResult.error("未传递文件路径");
        }else if(crmfile.getId()==null){
            return SaResult.error("未传递文件id");
        }
        minioService.deleteFile(crmfile.getUrl());
        //删除数据库中的数据
        fileService.removeById(crmfile);
        return SaResult.ok("删除成功");
    }
}
